package messages

import (
	"encoding/binary"
	"fmt"
	"io"
)

// RTPS消息头
type Header struct {
	ProtocolID      [4]byte  // "RTPS"
	ProtocolVersion Version
	VendorID        uint16
	GUIDPrefix      [12]byte
}

// 协议版本
type Version struct {
	Major uint8
	Minor uint8
}

// 子消息头
type SubmessageHeader struct {
	SubmessageID uint8
	Flags        uint8
	SubmessageLength uint16
}

// 序列化消息头
func (h *Header) Write(w io.Writer) error {
	if _, err := w.Write(h.ProtocolID[:]); err != nil {
		return err
	}
	if err := binary.Write(w, binary.BigEndian, h.ProtocolVersion.Major); err != nil {
		return err
	}
	if err := binary.Write(w, binary.BigEndian, h.ProtocolVersion.Minor); err != nil {
		return err
	}
	if err := binary.Write(w, binary.BigEndian, h.VendorID); err != nil {
		return err
	}
	_, err := w.Write(h.GUIDPrefix[:])
	return err
}

// 反序列化消息头
func (h *Header) Read(r io.Reader) error {
	if _, err := r.Read(h.ProtocolID[:]); err != nil {
		return err
	}
	if err := binary.Read(r, binary.BigEndian, &h.ProtocolVersion.Major); err != nil {
		return err
	}
	if err := binary.Read(r, binary.BigEndian, &h.ProtocolVersion.Minor); err != nil {
		return err
	}
	if err := binary.Read(r, binary.BigEndian, &h.VendorID); err != nil {
		return err
	}
	_, err := r.Read(h.GUIDPrefix[:])
	return err
}

// 验证消息头
func (h *Header) Validate() error {
	if string(h.ProtocolID[:]) != "RTPS" {
		return fmt.Errorf("invalid protocol ID: %s", string(h.ProtocolID[:]))
	}
	if h.ProtocolVersion.Major != 2 || h.ProtocolVersion.Minor != 2 {
		return fmt.Errorf("unsupported protocol version: %d.%d", 
			h.ProtocolVersion.Major, h.ProtocolVersion.Minor)
	}
	return nil
}